<template>
  <div class="cms-adv">
    <el-row>
      <el-col :span="24" class="file-tool">
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="$refs.modifycolumn.handleAdd()"
        >
          添加分类
        </el-button>
        <el-divider direction="vertical"></el-divider>
        <el-upload
          class="upload-btn"
          :show-file-list="false"
          :action="uploadUrl + '?columnId=' + selectColumn.id"
          :on-error="fileError"
          :before-upload="fileBefore"
          :on-success="fileSuccess"
        >
          <el-button
            type="primary"
            :loading="uploadLoading"
            icon="el-icon-upload2"
          >
            上传(
            <u>U</u>
            )
          </el-button>
        </el-upload>

        <el-button type="primary" icon="el-icon-download" @click="downUrl">
          下载(
          <u>W</u>
          )
        </el-button>
        <el-button type="primary" icon="el-icon-link" @click="copyUrl">
          复制地址
        </el-button>
        <el-divider direction="vertical"></el-divider>
        <el-button type="warning" icon="el-icon-set-up" @click="reNameFile">
          重命名(
          <u>R</u>
          )
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-document-copy"
          @click="copyFile"
        >
          复制(
          <u>C</u>
          )
        </el-button>
        <el-button type="primary" icon="el-icon-money" @click="moveFile">
          移动(
          <u>M</u>
          )
        </el-button>
        <el-button type="danger" icon="el-icon-close" @click="fileDelete">
          删除(
          <u>D</u>
          )
        </el-button>
        <el-button type="primary" icon="el-icon-finished" @click="fileSelect">
          确定选择( )
        </el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-select
          v-model="param.types"
          placeholder="请选择"
          @change="typeChange"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-input
          :value="param.path + selectColumn.enName"
          placeholder="请输入单行文本"
          :style="{ width: '500px', marginLeft: '20px' }"
        >
          <template slot="prepend">
            <i class="el-icon-folder-opened"></i>
          </template>
          <template slot="append">
            <i class="el-icon-refresh"></i>
          </template>
        </el-input>
      </el-col>
    </el-row>
    <el-row type="flex">
      <el-col class="code-left" :style="{ height: winHeight + 'px' }">
        <div class="title">
          <i class="el-icon-folder-opened"></i>
          文件分类
        </div>
        <div class="cur-tree">
          <el-tree
            :data="treeData"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            :render-content="renderContent"
            @node-click="columnnode"
          ></el-tree>
        </div>
      </el-col>
      <el-col class="code-right" :style="{ height: winHeight + 'px' }">
        <div v-if="imgData.length == 0" class="empty">
          <p><i class="el-icon-warning-outline"></i></p>
          无文件
        </div>
        <div
          v-for="it in imgData"
          :key="it.id"
          class="file-item"
          :class="it.id == imgSelect.id ? 'active' : ''"
          @click="selectedFile(it)"
        >
          <i class="el-icon-star-on"></i>
          <div class="file-info">
            <el-image
              v-if="isImg(it.fileType)"
              :src="serverUrl + it.fileUrl"
              :preview-src-list="resAttrImg(serverUrl + it.fileUrl)"
            ></el-image>
            <i
              v-if="!isImg(it.fileType)"
              class="file-preview"
              :class="'file-type-' + it.fileType"
            ></i>
          </div>
          <div class="file-title">
            <el-tooltip
              class="item"
              effect="dark"
              placement="bottom-start"
              :content="it.name"
            >
              <el-tag class="name">{{ it.name }}</el-tag>
            </el-tooltip>
          </div>
        </div>
      </el-col>
    </el-row>
    <modifycolumn
      ref="modifycolumn"
      @complete="onColumnComplete"
    ></modifycolumn>
    <el-dialog
      :title="moveDig.title"
      :visible.sync="moveDig.visible"
      width="30%"
    >
      <div class="movetree">
        <el-tree
          :data="treeData"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
          @node-click="movenode"
        ></el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="moveDig.visible = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="moveDig.loading"
          @click="moveSubmit"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import { baseURL } from '@/config'
  import modifycolumn from './modifycolumn'
  import { getList, deletes } from '@/api/sys/filecolumn'
  import {
    getFileList,
    filedeletes,
    filemove,
    filerename,
    filecopy,
  } from '@/api/sys/fileinfo'
  import { changeTree } from '@/utils/treeTool'
  export default {
    components: {
      modifycolumn,
    },
    data() {
      return {
        moveDig: {
          visible: false,
          loading: false,
          title: '请选择要移动到的栏目',
        },
        options: [
          {
            value: '',
            label: '根据类型搜索',
          },
          {
            value: 'all',
            label: '所有文件',
          },
          {
            value: 'file',
            label: '文件',
          },
          {
            value: 'image',
            label: '图片',
          },
        ],
        uploadLoading: false,
        uploadUrl: '',
        serverUrl: '',
        winHeight: window.innerHeight - 240,
        selectColumn: { enName: '', id: undefined },
        sourceData: [],
        treeData: [],
        imgExt: ['png', 'jpg', 'jpeg', 'bmp', 'gif'],
        param: {
          types: '',
          path: '/upload/file/',
          key: '',
          limit: 10,
          page: 1,
          id: '0',
        },
        imgData: [],
        imgSelect: {},
        moveColumn: {},
        copyOrmoveType: 1,
      }
    },
    mounted() {
      this.serverUrl = baseURL
      this.uploadUrl = baseURL + 'api/sys/fileinfo/update'
      this.init()
      this.initFile()
    },
    methods: {
      async init() {
        const t = await getList()
        this.sourceData = t.data
        let _tree = []
        t.data.some((m) => {
          _tree.push({
            id: m.id,
            value: m.id,
            label: m.name,
            enName: m.enName,
            parentId: m.parentId,
          })
        })
        this.treeData = changeTree(_tree)
      },
      async initFile() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.2)',
        })
        const t = await getFileList(this.param)
        this.imgData = t.data.items
        loading.close()
      },
      typeChange(v) {
        if (v) {
          this.param.types = v
          this.initFile()
        }
      },
      selectedFile(m) {
        if (m.id == this.imgSelect.id) {
          this.imgSelect = {}
          return
        }
        this.imgSelect = m
      },
      reNameFile() {
        if (!this.imgSelect.id) {
          this.$notify({
            message: '请选择文件在执行重命名操作~',
            type: 'warning',
          })
          return
        }
        this.$prompt('请输入文件新名称，更改文件名后原文件将无法访问', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: this.imgSelect.name,
        })
          .then(async ({ value }) => {
            const httpRes = await filerename({
              id: this.imgSelect.id,
              fileName: value,
            })
            if (httpRes.code != 200) {
              this.$message({
                type: 'error',
                message: httpRes.message,
              })
            } else {
              this.$message({
                type: 'success',
                message: '重命名成功~',
              })
              this.initFile()
            }
          })
          .catch(() => {})
      },
      moveFile() {
        if (!this.imgSelect.id) {
          this.$notify({
            message: '请选择文件在执行移动操作~',
            type: 'warning',
          })
          return
        }
        this.copyOrmoveType = 1
        this.moveDig.title = '请选择要移动到的栏目'
        this.moveDig.visible = true
      },
      async moveSubmit() {
        if (!this.moveColumn.id) {
          this.$notify({
            message: '请选择栏目信息',
            type: 'warning',
          })
          return
        }
        let param = { id: this.imgSelect.id, columnId: this.moveColumn.id }
        this.moveDig.loading = true
        let res = null,
          tipTitle = '文件移动成功'
        if (this.copyOrmoveType == 1) {
          res = await filemove(param)
        }
        if (this.copyOrmoveType == 2) {
          // const fileModel = this.sourceData.filter(
          //   (m) => m.id == this.imgSelect.columnId
          // )
          if (this.moveColumn.id == this.imgSelect.columnId) {
            this.$notify({
              message: '相同栏目下已存在相同的文件',
              type: 'warning',
            })
            this.moveDig.loading = false
            return
          }
          res = await filecopy(param)
          tipTitle = '文件复制成功'
        }
        this.moveDig.loading = false
        if (res.code == 200) {
          this.$notify({
            message: tipTitle,
            type: 'success',
          })
          this.moveDig.visible = false
          this.initFile()
        } else {
          this.$notify({
            message: res.message,
            type: 'error',
          })
        }
      },
      movenode(m) {
        this.moveColumn = m
      },
      copyFile() {
        if (!this.imgSelect.id) {
          this.$notify({
            message: '请选择文件在执行复制操作~',
            type: 'warning',
          })
          return
        }
        this.copyOrmoveType = 2
        this.moveDig.title = '请选择要复制到的栏目'
        this.moveDig.visible = true
      },
      fileDelete() {
        if (!this.imgSelect.id) {
          this.$notify({
            message: '请选择文件在执行删除操作~',
            type: 'warning',
          })
          return
        }
        var _this = this
        this.$confirm('确认要删除当前的文件吗？', '提示', {
          type: 'warning',
          customClass: 'f-cur-message',
        }).then(async () => {
          this.loading = true
          const res = await filedeletes(_this.imgSelect.id)
          this.loading = false
          if (res.code == 200) {
            this.$notify({
              message: '删除成功',
              type: 'success',
            })
            _this.initFile()
          } else {
            this.$notify({
              message: res.message,
              type: 'error',
            })
          }
        })
      },
      downUrl() {
        if (!this.imgSelect.id) {
          this.$notify({
            message: '请选择文件在执行下载操作~',
            type: 'warning',
          })
          return
        }
        const fileData = baseURL + this.imgSelect.fileUrl
        const url = window.URL.createObjectURL(
          new Blob([fileData], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
          })
        )
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', this.imgSelect.name)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      },
      copyUrl() {
        if (!this.imgSelect.id) {
          this.$notify({
            message: '请选择文件在执行复制链接操作~',
            type: 'warning',
          })
          return
        }
        var input = document.createElement('input')
        input.value = baseURL + this.imgSelect.fileUrl
        document.body.appendChild(input)
        input.select()
        document.execCommand('Copy')
        document.body.removeChild(input)
        this.$notify({
          message: '已将链接复制到粘贴板中~',
          type: 'success',
        })
      },
      remove(node, data) {
        var _this = this
        this.$confirm('确认要删除当前的文件分类吗？', '提示', {
          type: 'warning',
        }).then(async () => {
          this.loading = true
          const res = await deletes(data.id)
          this.loading = false
          if (res.code == 200) {
            this.$notify({
              message: '删除成功',
              type: 'success',
            })
            _this.init()
          } else {
            this.$notify({
              message: res.message,
              type: 'error',
            })
          }
        })
      },
      append(data) {
        var _model = {}
        this.sourceData.forEach((item) => {
          if (item.id == data.id) {
            _model = item
          }
        })
        this.$refs.modifycolumn.handelModify(_model)
      },
      onColumnComplete() {
        this.init()
      },
      columnnode(data, node, e) {
        this.selectColumn = data
        this.param.id = data.id
        this.initFile()
      },
      fileBefore(file) {
        if (!this.selectColumn.id) {
          this.$notify({
            message: '请选择文件分类上传文件~',
            type: 'warning',
          })
          return false
        }
        this.uploadLoading = true
      },
      fileSuccess(response, file, fileList) {
        this.uploadLoading = false
        if (response.code == 200) {
          this.initFile()
          this.$notify({
            message: '文件上传成功',
            type: 'success',
          })
        } else {
          this.$notify({
            message: response.message,
            type: 'error',
          })
        }
      },
      fileError(err, file, fileList) {
        this.uploadLoading = true
        this.$notify({
          message: err,
          type: 'error',
        })
      },
      fileSelect() {
        this.$emit('complete', this.imgSelect)
      },
      isImg(ext) {
        let isImg = false
        this.imgExt.forEach((m) => {
          if (m == ext) {
            isImg = true
          }
        })
        return isImg
      },
      resAttrImg(img) {
        let arr = []
        arr.push(img)
        return arr
      },
      renderContent(h, { node, data, store }) {
        return (
          <span class="custom-tree-node">
            <span>{node.label}</span>
            <span class="tool">
              <el-button
                icon="el-icon-edit"
                type="text"
                on-click={() => this.append(data)}
              ></el-button>
              <el-button
                icon="el-icon-delete"
                type="text"
                on-click={() => this.remove(node, data)}
              ></el-button>
            </span>
          </span>
        )
      },
    },
  }
</script>
<style lang="scss" scoped>
  @media only screen and (max-width: 768px) {
    .code-left {
      width: 100% !important;
      position: relative !important;
    }
    .code-right {
      width: 100% !important;
      left: 0px !important;
      padding: 0px !important;
      margin-top: 20px;
    }
  }
  .code-left {
    width: 260px;
    position: absolute;
    top: 10px;
    bottom: 0;
    float: inherit;
    background-color: #edf5ff;
    .title {
      height: 50px;
      line-height: 50px;
      padding-left: 20px;
      font-weight: bold;
      background-color: #dee5ef;
    }
  }
  .code-left::after {
    content: '';
    position: absolute;
    height: 1px;
    width: 100%;
    left: -19px;
    top: 0px;
    background-color: #f6f8f9;
  }
  .code-right {
    left: 260px;
    position: relative;
    width: calc(100% - 260px);
    top: 10px;
    bottom: 0;
    right: 0;
    float: inherit;
    padding: 0px 0px 10px 10px;
    flex: 1;
    display: flex;
    .empty {
      text-align: center;
      width: 80%;
      padding-top: 50px;
      i {
        font-size: 30px;
      }
    }
  }
  .code-right .file-item.active {
    background: #73a1d7;
    background: linear-gradient(
      to bottom,
      rgba(76, 168, 252, 0.8) 46%,
      rgba(37, 147, 252, 1) 100%
    );
    background: -webkit-linear-gradient(
      to bottom,
      rgba(76, 168, 252, 0.8) 46%,
      rgba(37, 147, 252, 1) 100%
    );
    .name {
      color: #ffffff;
    }
    .el-icon-star-on {
      display: block;
      color: #fbc010;
      position: absolute;
      right: 2px;
      top: 2px;
      z-index: 100;
      font-size: 18px;
    }
  }
  .code-right .file-item {
    width: 120px;
    height: 120px;
    margin: 0px 10px 10px 0;
    background-color: #f9f9f9;
    border: 1px solid #eeeeee;
    border-radius: 5px;
    position: relative;
    .el-icon-star-on {
      display: none;
    }
    .file-info {
      padding: 5px;
      height: 80px;
      text-align: center;
      img {
        max-width: 110px;
        max-height: 80px;
      }
    }
    .file-title {
      height: 30px;
      line-height: 30px;
      overflow: hidden;
      text-align: center;
      font-size: 12px;
      padding: 0px 5px;
      .name {
        border-width: 0px !important;
        background-color: transparent !important;
        padding: 0px !important;
      }
    }
    i.file-preview {
      display: inline-block;
      width: 70px;
      height: 70px;
      background: url('~@/assets/file-icons.png') no-repeat;
      position: relative;
      top: 5px;
    }
    i.file-preview.file-type-zip,
    i.file-preview.file-type-rar,
    i.file-preview.file-type-7z,
    i.file-preview.file-type-tar,
    i.file-preview.file-type-gz,
    i.file-preview.file-type-bz2 {
      background-position: -280px center;
    }
    i.file-preview.file-type-xls,
    i.file-preview.file-type-xlsx {
      background-position: -355px center;
    }
    i.file-preview.file-type-doc,
    i.file-preview.file-type-docx {
      background-position: -420px center;
    }
    i.file-preview.file-type-ppt,
    i.file-preview.file-type-pptx {
      background-position: -490px center;
    }
    i.file-preview.file-type-pdf {
      background-position: -630px center;
    }
    i.file-preview.file-type-file {
      background-position: -140px center;
    }
    i.file-preview.file-type-dir {
      background-position: 0 center;
    }
    i.file-preview.file-type-txt,
    i.file-preview.file-type-md,
    i.file-preview.file-type-json,
    i.file-preview.file-type-htm,
    i.file-preview.file-type-xml,
    i.file-preview.file-type-html,
    i.file-preview.file-type-js,
    i.file-preview.file-type-css,
    i.file-preview.file-type-php,
    i.file-preview.file-type-jsp,
    i.file-preview.file-type-asp {
      background-position: -700px center;
    }
    i.file-preview.file-type-ogg,
    i.file-preview.file-type-wav,
    i.file-preview.file-type-wmv,
    i.file-preview.file-type-mid,
    i.file-preview.file-type-mp3 {
      background-position: -1050px center;
    }
    i.file-preview.file-type-mp4,
    i.file-preview.file-type-swf,
    i.file-preview.file-type-mkv,
    i.file-preview.file-type-avi,
    i.file-preview.file-type-flv,
    i.file-preview.file-type-mov,
    i.file-preview.file-type-mpg,
    i.file-preview.file-type-mpeg,
    i.file-preview.file-type-ogv,
    i.file-preview.file-type-webm,
    i.file-preview.file-type-rm,
    i.file-preview.file-type-rmvb {
      background-position: -980px center;
    }
  }
  .upload-btn {
    display: inline-block;
    margin-right: 10px;
  }
</style>
<style lang="scss">
  .cur-tree .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .cur-tree .el-tree {
    background: transparent;
  }
  .el-tree-node__content {
    height: 35px;
  }
  .cur-tree .tool {
    display: inline-block;
    padding-right: 10px;
    position: relative;
    z-index: 10;
  }
  .cur-tree .tool button {
    margin-left: 10px;
    font-size: 16px;
  }
  .el-icon-c-scale-to-original {
    font-size: 18px;
    position: relative;
    top: 2px;
  }
  .cms-adv .add-column {
    padding: 8px !important;
    float: right;
    margin: 8px;
  }
  .el-icon-folder-opened {
    font-size: 18px;
  }
  .file-tool {
    background-color: #f5f5f5;
    padding: 0px 5px 10px 5px;
    margin-bottom: 8px;
  }
  .file-tool .el-button {
    padding: 10px;
    border-radius: 8px;
  }
  .file-tool .el-button i {
    display: block;
    margin-bottom: 2px;
    font-size: 18px;
  }
  .file-tool .el-divider {
    margin: 0 12px;
    top: 6px;
    height: 47px;
  }
  .f-cur-message,
  .el-message-box__wrapper {
    z-index: 3000 !important;
  }
</style>
